package com.market.interceptor;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;

@Component
public class CrossOriginInterceptor implements HandlerInterceptor {
    private static final Logger logger = LoggerFactory.getLogger(CrossOriginInterceptor.class);

    public CrossOriginInterceptor(){
        logger.info("初始化 CrossOriginInterceptor");
    }
    
    //请求前拦截
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        String requestURI = request.getRequestURI();
        String method = request.getMethod();
        logger.info("CrossOriginInterceptor处理请求: {} {}", method, requestURI);

        //设置响应数据格式及编码
        response.setContentType("application/json;charset=UTF-8");
        
        //跨域处理
        String origin = request.getHeader("Origin");
        logger.info("请求Origin: {}", origin);
        
        if (origin != null) {
            // 只有当请求头中有Origin时才设置CORS头，避免与CorsFilter冲突
            response.setHeader("Access-Control-Allow-Origin", origin);
            response.setHeader("Access-Control-Allow-Methods", "POST, GET, OPTIONS, DELETE, PUT");
            response.setHeader("Access-Control-Max-Age", "3600");
            response.setHeader("Access-Control-Allow-Headers", "Content-Type, x-requested-with, Authorization, token");
            response.setHeader("Access-Control-Allow-Credentials", "true");
            logger.info("已设置CORS响应头");
        }
        
        // 对于OPTIONS请求，直接返回成功
        if ("OPTIONS".equalsIgnoreCase(method)) {
            logger.info("处理OPTIONS预检请求，直接返回成功");
            response.setStatus(HttpServletResponse.SC_OK);
            return false;
        }
        
        // 特殊处理登录请求
        if (requestURI.contains("/user/login")) {
            logger.info("处理登录请求，不做额外限制");
        }

        // 放行请求
        logger.info("CrossOriginInterceptor放行请求");
        return true;
    }

    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
        // 请求处理完成后的操作
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        // 请求完成后的操作
    }
}
